#!C:\Perl\bin\perl
use strict;

use Data::Dumper;
use File::Slurp;
use Ball;
use interaction;
use file_IO;
use UI;
use subs qw(output);
 use CGI::Ajax;
 use CGI;

%::game; #we can use this to store game settings - or do you think those shoudl go to data as well?

my $xml = new XML::Simple;
my $data = $xml->XMLin("data.xml", forcearray=>['character']);#open_data_file($ARGV[0]); #I suppose this is static data only
my $all_data = $xml->XMLin("inter.xml", forcearray=>['phrase','state','transition'], keyattr=>['name']); #and this maybe dynamic data

$::game{debug}=0;
$::cgi=1;

$ARGV[0]=~/-d/ and $::game{debug}=1;
$ARGV[0]=~/-l/ and $::cgi=0; # l, because lllocal, get it?


my $wojak = new Ball(3,-10,["plunger","kippah","axe","Camembert","ion","Hitler's Left Ball in a Jar"]);
$::cgi and $wojak->loadme();
$::cgi and $all_data=load("saveinter.xml");

my %actions = ( "w" => sub { $wojak->{y}++ if ( $wojak->can_go($data,0,1) ); } ,
                "s" => sub { $wojak->{y}-- if ( $wojak->can_go($data,0,-1) ); } ,
                "a" => sub { $wojak->{x}-- if ( $wojak->can_go($data,-1,0) ); } ,
                "d" => sub { $wojak->{x}++ if ( $wojak->can_go($data,1,0) ); } ,
                "i" => sub { $::returndiv.=$wojak->print_inv(); } ,
                "m" => sub { $wojak->show_map($data); } ,
                "q" => sub { exit(); } ,
                "l" => sub { $wojak->look($data); } ,
                "t" => sub { talk($wojak,$data); } ,
                "u" => sub { interaction("Yourself", $wojak); } ,
                "save" => sub { save("saveinter.xml", $all_data); $wojak->saveme();} ,
                "load" => sub { $all_data=load("saveinter.xml"); $wojak->loadme();} ,
                "dump" => sub { open(LOG,'>'."dump.txt");print LOG Dumper($all_data); },
                "slurpdump" => sub {  write_file 'mydump.log', Dumper( $all_data ); }

                 );
$::cgi or THE_GAME();


  sub THE_GAME2 {
    my $input = shift;
     return "jajaja\njajaja";

    # see if input is defined
    if ( not defined $input ) {
      return("input not defined or NaN");
    }

    # see if value is a number (*thanks Randall!*)
    if ( $input !~ /\A\d+\z/ ) {
      return("input is NaN");
    }

    # got a number, so mod by 2
    $input % 2 == 0 ? return("EVEN") : return("ODD");
  }

sub THE_GAME()
{
        $::returndiv="";
	my $here = $wojak->get_loc($data);

	if ($::cgi==1)
        {
            $::returndiv.="\nYou're in $here. ";
            $::returndiv.=$data->{region}->{$here}->{description} if $data->{region}->{$here}->{description}."<br>";
        }
        else
        {
          output; output "--------",2;
          output ("\nYou're in $here. ",1);

	  output ($data->{region}->{$here}->{description}, 1) if $data->{region}->{$here}->{description};
        }  

	#$data->{region}->{$here}->{dev} and output("I couldn't come up with a good idea for this country. I am not a clever man. If you can think of anything interesting, tell us.",1);
        $::returndiv.=print_characters($here)."\n" if $here ne 'Unknown'; #This prevents the Unknown problem



	my $in="hurr";
        if ($::cgi)
        {
          $in = shift;
          output "EINGABE: $in";
        } else
        {
          print "What do? >";
	$in = &input;
		chop($in);chop($in);
        }
	my $commandfound=0;

        $in =~ /^go to ([\w\s\.]*)/ and $wojak->go($all_data, $here, $1) and $commandfound=1;
        $in =~ /^talk to ([\w\s\.]*)/ and $wojak->talkto($all_data, $here, $1) and $commandfound=1;
	if ($actions{$in}) {&{$actions{$in}};$commandfound=1} 
	$commandfound or output "wut o_O",1;
	$::cgi and $wojak->saveme();
	$::cgi and save("saveinter.xml", $all_data);
         $::cgi and return $::returndiv;
	$::cgi or THE_GAME(); #the game never stops
}









  
    sub Show_HTML {
    my $html = <<'EOHTML';
<!DOCTYPE html>
<!-- saved from url=(0030)http://cektkp.com/cmd/#service -->
<html dir="ltr" lang="en-US"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="UTF-8">
<title>Command Line Website</title>
<meta name="description" content="cekTKp Command is a website that has no GUI, it just like MS-DOS command prompt in Windows or console terminal in Linux. Sorry your mouse is a bit useless here">
<meta name="keywords" content="command,cmd,command line,ms-dos,console,terminal,DOS prompt,command prompt">
<link rel="shortcut icon" href="http://cektkp.com/cmd/favicon.ico" type="image/x-icon">
<link rel="icon" href="http://cektkp.com/cmd/favicon.gif" type="image/gif">
<meta property="og:title" content="Command Line Website">
<meta property="og:type" content="website">
<meta property="og:url" content="http://cektkp.com/cmd">
<meta property="og:image" content="http://cektkp.com/cmd/images/cmd.gif">
<meta property="og:description" content="cekTKp Command is a website that has no GUI, it just like MS-DOS command prompt in Windows or console/terminal in Linux. Sorry your mouse is a bit useless here">
<meta property="og:site_name" content="Command Line">


<link href="/Command Line Website_files/css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="/Command Line Website_files/style.css" type="text/css">
<script type="text/javascript" src="/Command Line Website_files/jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="/Command Line Website_files/jquery.disable.text.select.js"></script>
<script type="text/javascript" src="/Command Line Website_files/jquery.contextmenu.r2.js"></script>
<script type="text/javascript" src="/Command Line Website_files/highlight.js"></script>
<script type="text/javascript" src="/Command Line Website_files/jsapi"></script>

<script type="text/javascript">
google.load("language", "1");
</script><script src="/Command Line Website_files/saved_resource" type="text/javascript"></script><script src="/Command Line Website_files/default+de.I.js" type="text/javascript"></script>



<script type="text/javascript">
$(document).ready(function(){
$(document).click(function(){
	$('#command').focus();
});
$('#command').focus();

var XMLHttp;
var reply;
if(navigator.appName == "Microsoft Internet Explorer") {
XMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
} else {
XMLHttp = new XMLHttpRequest();
}
function show_sun_rise () {
append_reply("lol");
reply = XMLHttp.open("GET", "/cgi-bin/example.pl", true);
append_reply(reply);
XMLHttp.onreadystatechange = function() {
if (XMLHttp.readyState == 4) {
document.getElementById( 'time_div' ).innerHTML = XMLHttp.responseText;
}
}
XMLHttp.send(null);
}

function append_reply(reply){
	$('#reply').css('padding','5px 0'); 
	$('#reply').append('<div class="lastcommand" style="margin:5px 0">root@takien.com:~$<span class="lastcmd">'+userinput()+'</span></div>'+reply);
	$('#command').val('');
	$('#command_copy').text('');
	$('#loading').text('~$');
	$('html, body').animate({scrollTop: $('#wrapper').height()}, 800);
	$('#reply').highlight('@cektkp');
}
if(window.location.hash){
	var lochash = window.location.hash.replace('#','');
	$('#command').val(unescape(lochash));
}
function userinput(){
	return $('#command').val().toLowerCase();
}
function is_numeric(s){
	if(s==undefined){
	return false;
   }
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;
   for (i = 0; i < s.length && IsNumber == true; i++){ 
      Char = s.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) {
         IsNumber = false;
         }
      }
   return IsNumber;
}


$('#command').keydown(function(e) {
	//entar
var command 	= userinput().split(' ')[0];
var totranslate = (userinput().split("'")[1]!=undefined)?userinput().split("'")[1]:'';
var param 	= userinput().replace(totranslate,'').replace(command,'').replace(" '' ",'').split(' ');
	if(e.ctrlKey && e.keyCode == 13) {
		window.location = command;
    }
	else if(e.keyCode == 13) {
	if(command.length < 1){
		append_reply('<div>You did not type anything</div>');
	}
	else if(command == 'clear'){
		$('#reply').css('padding','0');
		$('#reply,#command_copy').text('');
		$('#command').val('');
		window.location.hash = '';
		$('html, body').animate({scrollTop: $('#wrapper').height()}, 1000);
	}
	else if(command == 'print'){
		window.print();
	}
	else if(command == 'reload'){
		window.location='http://cektkp.com/cmd/';
	}
	else if(command == 'hello'){
		show_sun_rise();
	}
	else if(command == 'translate'){
		var sc	= param[0];
		var tg	= param[1];
		if((sc !='')  && (tg !='')){
		 google.language.translate(totranslate, sc, tg, function(rs) {
			if (rs.translation) {
			  var tr = rs.translation;
			  append_reply(tr);
			}
			}); 
		}
		else{
		append_reply('invalid param, use: translate \'original text\' source_lang target_lang');
		}
	}
	else{
		var data = '';
		if((command == 'twitter') && (param[1] == 'reply')){
			if(is_numeric(param[2])){
				reply_id = $('.tweet_'+param[2]).last().attr('id');
				data = 'command='+$('#command').val()+'&reply_to='+reply_id;
			}
			else{
				data == '';
			}
		}
		else{
			data = 'command='+$('#command').val();
		}
		$('#command_copy').text('');
		$('#loading').html('<img src="http://cektkp.com/cmd/images/loading.gif" alt="~$" />');
		$.ajax({
		type: "POST",
		url: "command.php",
		data: data,
		success: function(reply){
		append_reply(reply); 
		},
		error: function(request, status, error){
        if(request.responseText!=undefined){
		append_reply('Error: Request failed, try again');
		}
		}

		});
	}
	window.location.hash = command+' '+(totranslate?"'"+totranslate+"' ":'')+param.join(' ');
	}
	else if(e.keyCode == 38){
		$('#command').val($('.lastcmd').last().text());
		$('#command_copy').text($('.lastcmd').last().text());
		$('#command').css('width',(($('#command_copy').width()!=0)?$('#command_copy').width():1));
		}
	else if(e.keyCode == 27){
		$('#command').val('');
		$('#command_copy').text('');
	}
});
$(document).keyup(function(e){
if(e.keyCode == 27){
		$('#command').val('');
		$('#command_copy').text('');
}
else if(e.keyCode == 34){
$('html, body').animate({scrollTop: $('#wrapper').height()}, 1000);
}
else if(e.keyCode == 33){
$('html, body').animate({scrollTop: -$('#wrapper').height()}, 1000);
}
});
//caret caret
$('#command').css('width',(($('#command_copy').width()!=0)?$('#command_copy').width():1));
$('#command_copy').text($('#command').val());

$('#command').keyup(function(){
	$('#command_copy').text($(this).val());
	$(this).css('width',(($('#command_copy').width()!=0)?$('#command_copy').width():1));
});

//
//scroll test
$('html, body').animate({scrollTop: $('#wrapper').height()}, 800);
$('html, body').disableTextSelect();
$('html, body').contextMenu('rightmenu', {
      menuStyle: {
        border: '1px outset #000000'
      },
      itemStyle: {
        backgroundColor : '#d4d0c8',
        color: 'black',
		border: 'none',
		padding: '5px 5px 5px 10px'
      },
      itemHoverStyle: {
        color: '#fff',
        backgroundColor: '#0a246a',
        border: 'none'
      }
    });
}); 
</script>

<script id="__isTpiViewExists"></script>

<link rel="stylesheet" type="text/css" href="chrome-extension://ojpijjmpahflnipadmlpgbjmagmjchkk/css/about.css"></head><style type="text/css" id="CWToolbarStyle">html { padding-top: 34px !important;}</style>
<body id="body">
<div id="wrapper">
<pre>_____________________________________________________ 
Welcome to Cektkp Command - Command Line Website beta 0.1
(C) Copyright 2010 by Takien.com
* type help for hints
`````````````````````````````````````````````````````

<div id="reply" style="padding: 5px 0px; "><div class="lastcommand" style="margin:5px 0">root@takien.com:~$<span class="lastcmd">help</span></div><pre>Here is the basic command you can use, all command should be lowercase

Basic command:
-------------
help             display this help
goto &lt;link&gt;      go to url
clear            clear screen
reload           reload page
service          list all available services
exit             escape from here

Keyboard shortcut:
------------------
[enter]			execute current command
[arrow up]		repeat last command (if available)
[esc]			clear current command
[page up]		scroll screen to top
[page down]		scroll screen to bottom
</pre>
<div class="lastcommand" style="margin:5px 0">root@takien.com:~$<span class="lastcmd">service</span></div><pre>
Here is list of available service:

whois DOMAIN          whois service
ping  DOMAIN/IP        ping service
unixtime               display current unix time
date                   display current date
rand                   display random number, rand min max
calc                   simple calculator (experimental, may not work as expected :D)
sms NUMBER MESSAGE     sending SMS message to mobile phone
ip                     check your ip address
translate              use: translate 'text' source_lang dest_lang
twitter                twiter appliccation, type 'twitter help' for info
</pre></div>
    <div id=resultdiv>
    </div>
<div id="user">root@takien.com:<span id="loading">~$</span></div><div id="command_copy"></div>
<div class="clear"></div>
<input spellcheck="false" autofocus="autofocus" type="text" tabindex="1" id="command" style="width: 56px; "onKeyDown="if(event.keyCode==13) evenodd( ['command'], ['resultdiv'] );">
</pre>

<div class="contextMenu" id="rightmenu" style="display: none; ">
<ul>
  <li id="share"><a onclick="javascript:window.open(&#39;http://facebook.com/share.php?u=http://cektkp.com/cmd&#39;,&#39;Share this&#39;,
 &#39;width=500,height=400,menubar=yes,status=yes,location=yes,toolbar=no,scrollbars=no&#39;);return false" target="_blank" href="http://facebook.com/share.php?u=http://cektkp.com/cmd">Share</a></li> 
  <li id="item_1">Mark</li>
  <li id="item_2">Copy</li>
  <li id="item_3">Paste</li>
  <li id="item_4">Select All</li>
  <li id="item_5">Scroll</li>
  <li id="item_6">Find...</li>
</ul>
</div>


</div><div id="jqContextMenu" style="position: absolute; z-index: 500; display: block; left: 1700px; top: 231px; "><ul style="list-style: none; padding: 1px; margin: 0px; background-color: rgb(255, 255, 255); border: 1px outset rgb(0, 0, 0); width: 100px; ">
  <li id="share" style="margin: 0px; color: black; display: block; cursor: default; padding: 5px 5px 5px 10px; border: none; background-color: rgb(212, 208, 200); "><a onclick="javascript:window.open(&#39;http://facebook.com/share.php?u=http://cektkp.com/cmd&#39;,&#39;Share this&#39;,
 &#39;width=500,height=400,menubar=yes,status=yes,location=yes,toolbar=no,scrollbars=no&#39;);return false" target="_blank" href="http://facebook.com/share.php?u=http://cektkp.com/cmd">Share</a></li> 
  <li id="item_1" style="margin: 0px; color: black; display: block; cursor: default; padding: 5px 5px 5px 10px; border: none; background-color: rgb(212, 208, 200); ">Mark</li>
  <li id="item_2" style="margin: 0px; color: black; display: block; cursor: default; padding: 5px 5px 5px 10px; border: none; background-color: rgb(212, 208, 200); ">Copy</li>
  <li id="item_3" style="margin: 0px; color: black; display: block; cursor: default; padding: 5px 5px 5px 10px; border: none; background-color: rgb(212, 208, 200); ">Paste</li>
  <li id="item_4" style="margin: 0px; color: black; display: block; cursor: default; padding: 5px 5px 5px 10px; border: none; background-color: rgb(212, 208, 200); ">Select All</li>
  <li id="item_5" style="margin: 0px; color: black; display: block; cursor: default; padding: 5px 5px 5px 10px; border: none; background-color: rgb(212, 208, 200); ">Scroll</li>
  <li id="item_6" style="margin: 0px; color: black; display: block; cursor: default; padding: 5px 5px 5px 10px; border: none; background-color: rgb(212, 208, 200); ">Find...</li>
</ul></div><div style="background-color: rgb(0, 0, 0); position: absolute; opacity: 0.2; z-index: 499; display: block; width: 104px; height: 151px; left: 1702px; top: 233px; "></div><div class="SkipThisFixedPosition top-iframe-wrapper" style="width: 100%; height: 34px; position: fixed; left: 0px; top: 0px !important; z-index: 99997; "><iframe style="width: 100%; height: 34px; top: 0px; left: 0px; " src="/Command Line Website_files/container.htm" scrolling="no" class="toolbarContainer" frameborder="0px" id="CWTBiframe0"></iframe></div><div id="mainContainer_CTID"><div class="fixedDiv SkipThisFixedPosition UrlGadgetsDiv" style="position: fixed; left: 0px; z-index: 2147483640; top: 34px !important; "></div><div class="fixedDiv SkipThisFixedPosition GeneralGadgetsDiv" style="position: fixed; left: 0px; z-index: 2147483640; width: 100%; top: 34px !important; "><div class="minzX_34" style="top: 0px; left: 12px; position: absolute !important; z-index: 2147483645; display: none; "><iframe id="uid128520830028304211" frameborder="0px" scrolling="no" class="iframeGadget undefined" src="/Command Line Website_files/menuPanel.htm" style="top: 0px; left: 0px; visibility: visible !important; width: 157px; position: absolute; display: none; height: 344px; "></iframe></div><div class="minzX_847" style="top: 34px; left: 847px; position: absolute !important; z-index: 2147483646; width: 184px; height: 225px; display: none; "><iframe id="1340033982960" frameborder="1px" scrolling="no" class="iframeGadget" src="/Command Line Website_files/dynamicMenu.htm" style="top: 34px; left: 847px; visibility: visible !important; display: none; width: 184px; height: 225px; "></iframe></div></div></div></body></html>
EOHTML
    return $html;
  }
  
  
my $cgihandle = new CGI();
my $pjx = new CGI::Ajax( 'evenodd' => \&THE_GAME );
  
$::cgi and print $pjx->build_html($cgihandle,\&Show_HTML);
